#include "head.h"

void *threadMain(void *p) {
    pool_t *pool = (pool_t *)p;
    MYSQL mysql;
    while (1)
    {
        pthread_mutex_lock(&pool->lock);
        // 等待队列中有任务
        while (pool->queue.size == 0 && pool->exitFlag == 0) {
            pthread_cond_wait(&pool->cond, &pool->lock);
        }
        // 退出线程
        if (pool->exitFlag == 1) {
            // 关闭数据库连接
            mysql_close(&mysql);

            pthread_mutex_unlock(&pool->lock);
            pthread_exit(NULL);
        }
        // 取出任务
        int net_fd = pool->queue.head->net_fd;
        deQueue(&pool->queue);

        // 初始化数据库
        mysql_init(&mysql);
        // 连接数据库   
        char mysql_user[60] = {0};
        load_config("mysql_user", mysql_user);
        char mysql_password[60] = {0};
        load_config("mysql_password", mysql_password);
        char mysql_db[60] = {0};
        load_config("mysql_db", mysql_db);

        printf("mysql_user_name %s\n", mysql_user);
        printf("mysql_password %s\n", mysql_password);
        printf("mysql_db %s\n", mysql_db);
        mysql_real_connect(&mysql, "localhost", mysql_user, mysql_password, mysql_db, 0, NULL, 0);
        printf("connect: %s \n", mysql_error(&mysql));
       //测试用的写入语句
       //mysql_query(&mysql, "insert into users (username,salt,password_hash,enroll_time) values ('cai',111,password_hash,now())");
        //printf("query: %s \n", mysql_error(&mysql));
        pthread_mutex_unlock(&pool->lock);

        // 处理任务
        printf("begin serve\n");
        analyze_cmd(net_fd, &mysql);
        printf("close serve\n");
    }

    return NULL;
}
